package zuo.algo.c12;

/**
 * 00:03-岛问题
 * 一个矩阵中只有0和1两种值，每个位置可以和上下左右四个位置相连，如果有1连成一片就是一个岛，求矩阵中有几个岛？
 * 例：
 * 001010
 * 111010
 * 100100
 * 000000
 * 该矩阵中有三个岛
 */
public class Islands {

    public static int countIslands(int[][] arr) {
        if (arr == null || arr[0] == null) {
            return 0;
        }
        int n = arr.length;
        int m = arr[0].length;
        int res = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (arr[i][j] != 1) {
                    continue;
                }
                res++;
                infect(arr, i, j, n, m);
            }
        }
        return res;
    }

    private static void infect(int[][] arr, int i, int j, int n, int m) {
        if (i < 0 || i >= n || j < 0 || j >= m || arr[i][j] != 1) {
            return;
        }
        arr[i][j] = 2;
        infect(arr, i - 1, j, n, m);
        infect(arr, i + 1, j, n, m);
        infect(arr, i, j - 1, n, m);
        infect(arr, i, j + 1, n, m);
    }

    public static void main(String[] args) {
        int[][] arr = {
                {0, 0, 1, 0, 1, 0},
                {1, 1, 1, 0, 1, 0},
                {1, 0, 0, 1, 0, 0},
                {0, 0, 0, 0, 0, 0}
        };
        int res = countIslands(arr);
        System.out.println(res);

        int m = arr[0].length;
        for (int[] ints : arr) {
            for (int j = 0; j < m; j++) {
                System.out.print(ints[j]);
            }
            System.out.println();
        }
    }
}
